ReactJS Ultra For Beginners

🪝 Custom Hooks


What are Custom Hooks?

  • Functions that start with "use" and can call other hooks
  • Allow you to extract component logic into reusable functions
  • Share stateful logic between components
  • Keep components clean and focused

📝 Basic Syntax

import { useState, useEffect } from "react"; // Custom hook function useCounter(initialValue = 0) { const [count, setCount] = useState(initialValue); const increment = () => setCount(count + 1); const decrement = () => setCount(count - 1); const reset = () => setCount(initialValue); return { count, increment, decrement, reset }; } // Usage in component function Counter() { const { count, increment, decrement, reset } = useCounter(10); return ( <div> <p>Count: {count}</p> <button onClick={increment}>+</button> <button onClick={decrement}>-</button> <button onClick={reset}>Reset</button> </div> ); }

🔑 Naming Convention

✅ Good:

function useCounter() {} function useLocalStorage() {} function useWindowSize() {} function useDebounce() {}

❌ Bad:

function counter() {} function getCounter() {} function useCounterHook() {}

🎯 Common Custom Hooks

1. useLocalStorage:

function useLocalStorage(key, initialValue) { const [storedValue, setStoredValue] = useState(() => { try { const item = window.localStorage.getItem(key); return item ? JSON.parse(item) : initialValue; } catch (error) { console.error(error); return initialValue; } }); const setValue = (value) => { try { const valueToStore = value instanceof Function ? value(storedValue) : value; setStoredValue(valueToStore); window.localStorage.setItem(key, JSON.stringify(valueToStore)); } catch (error) { console.error(error); } }; return [storedValue, setValue]; } // Usage function UserProfile() { const [user, setUser] = useLocalStorage("user", null); return ( <div> {user ? ( <p>Welcome, {user.name}!</p> ) : ( <button onClick={() => setUser({ name: "John" })}>Login</button> )} </div> ); }

2. useWindowSize:

function useWindowSize() { const [windowSize, setWindowSize] = useState({ width: window.innerWidth, height: window.innerHeight, }); useEffect(() => { function handleResize() { setWindowSize({ width: window.innerWidth, height: window.innerHeight, }); } window.addEventListener("resize", handleResize); return () => window.removeEventListener("resize", handleResize); }, []); return windowSize; } // Usage function ResponsiveComponent() { const { width, height } = useWindowSize(); return ( <div> <p> Window size: {width} x {height} </p> {width < 768 && <p>Mobile view</p>} </div> ); }

3. useDebounce:

function useDebounce(value, delay) { const [debouncedValue, setDebouncedValue] = useState(value); useEffect(() => { const handler = setTimeout(() => { setDebouncedValue(value); }, delay); return () => { clearTimeout(handler); }; }, [value, delay]); return debouncedValue; } // Usage function SearchInput() { const [searchTerm, setSearchTerm] = useState(""); const debouncedSearchTerm = useDebounce(searchTerm, 500); useEffect(() => { if (debouncedSearchTerm) { // Perform search searchAPI(debouncedSearchTerm); } }, [debouncedSearchTerm]); return ( <input value={searchTerm} onChange={(e) => setSearchTerm(e.target.value)} placeholder="Search..." /> ); }

4. useFetch:

function useFetch(url) { const [data, setData] = useState(null); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); useEffect(() => { const fetchData = async () => { try { setLoading(true); const response = await fetch(url); const result = await response.json(); setData(result); } catch (err) { setError(err); } finally { setLoading(false); } }; fetchData(); }, [url]); return { data, loading, error }; } // Usage function UserList() { const { data: users, loading, error } = useFetch("/api/users"); if (loading) return <div>Loading...</div>; if (error) return <div>Error: {error.message}</div>; if (!users) return <div>No users found</div>; return ( <ul> {users.map((user) => ( <li key={user.id}>{user.name}</li> ))} </ul> ); }

🔧 Advanced Patterns

Hook with Parameters:

function useToggle(initialValue = false) { const [value, setValue] = useState(initialValue); const toggle = () => setValue(!value); const setTrue = () => setValue(true); const setFalse = () => setValue(false); return { value, toggle, setTrue, setFalse }; } // Usage function ToggleButton() { const { value, toggle } = useToggle(false); return <button onClick={toggle}>{value ? "ON" : "OFF"}</button>; }

Hook with Callbacks:

function useInterval(callback, delay) { const savedCallback = useRef(); useEffect(() => { savedCallback.current = callback; }, [callback]); useEffect(() => { if (delay !== null) { const id = setInterval(() => savedCallback.current(), delay); return () => clearInterval(id); } }, [delay]); } // Usage function Timer() { const [count, setCount] = useState(0); useInterval(() => { setCount((c) => c + 1); }, 1000); return <div>Count: {count}</div>; }

Composing Hooks:

function useUser(userId) { const { data: user, loading, error } = useFetch(`/api/users/${userId}`); const [userPreferences, setUserPreferences] = useLocalStorage( `user-${userId}-preferences`, {} ); return { user, userPreferences, setUserPreferences, loading, error, }; }

⚠️ Rules of Custom Hooks

  1. Always start with "use" - React uses this to identify hooks
  2. Only call hooks at the top level - not inside loops, conditions, or nested functions
  3. Only call hooks from React functions - not regular JavaScript functions
  4. Return values consistently - same structure every time
  5. Handle cleanup - use useEffect cleanup functions when needed

🎯 Best Practices

  1. Keep hooks focused - one concern per hook
  2. Use descriptive names - make the purpose clear
  3. Handle edge cases - null checks, error handling
  4. Document your hooks - explain parameters and return values
  5. Test your hooks - write tests for complex logic
  6. Reuse existing hooks - compose hooks when possible